package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //设置请求的编码，告诉servlet按照什么格式来理解请求
        req.setCharacterEncoding("utf8");
        //设置响应的编码，告诉servlet按照什么格式来理解响应
       //resp.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        //1.读取用户名和密码
        //如果用户名密码包括中文可能会出现问题
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if (username == null || "".equals(username) || password == null || "".equals(password)) {
            String html="<h3>登录失败！，缺少username或者password</h3>";
            resp.getWriter().write(html);
            return;
        }
        //2.读取数据库，查看用户名是否存在，密码是否匹配
        UserDao userDao=new UserDao();
        User user=userDao.SelectByUsername(username);
        if (user==null){
            String html="<h3>登录失败，当前用户名或密码不正确</h3>";
            resp.getWriter().write(html);
            return;
        }
        if(!password.equals(user.getPassword())){
            String html="<h3>登录失败，当前用户名或密码不正确</h3>";
            resp.getWriter().write(html);
            return;
        }
        //3.验证通过，创建会话保存用户信息
        HttpSession session=req.getSession(true);
        session.setAttribute("user",user);
        //4.重定向
        resp.sendRedirect("blong.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        //通过这个方法获取到用户的登录状态
        HttpSession session=req.getSession(false);
        if(session==null){
            User user=new User();
            String respJson=objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        User user=(User) session.getAttribute("user");
        if(user==null){
            user=new User();
            String respJson=objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        //成功取出
        String respJson=objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
